import { Component } from '@angular/core';
import { NavController,ViewController,ToastController,LoadingController} from 'ionic-angular';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';

import {UserService} from "../../providers/UserService";
import {Login} from '../login/login'
@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class Signup {
	signupForm: FormGroup;
	phone: any;
	password:any;
  confirmPassword:any;

  constructor(
  	public navCtrl: NavController,
  	public viewCtrl:ViewController,
  	private formBuilder: FormBuilder,
  	public loadingCtrl : LoadingController,
    private toastCtrl  : ToastController,
    private userService:UserService,) {

  	this.signupForm = formBuilder.group({
  		phone:['', Validators.compose([Validators.required,Validators.maxLength(11), Validators.minLength(11)])],
      password:['', Validators.compose([Validators.required, Validators.minLength(6)])],
      confirmPassword:['', Validators.compose([Validators.required, Validators.minLength(6)])],
  	})
    this.phone = this.signupForm.controls['phone'];
    this.password = this.signupForm.controls['password'];
    this.confirmPassword = this.signupForm.controls['confirmPassword'];

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Signup');
  }
  //关闭窗口
  dismiss(){
  	this.viewCtrl.dismiss();
  }
  //注册
  register(value){

    // 验证密码是否一致
    if(value.password!=null && value.confirmPassword!= value.password){
      this.toastCtrl.create({message: "两次密码不一致", duration: 3000}).present();
      return false;
    }
    let loader = this.loadingCtrl.create({
      content: "正在注册...",
      duration: 3000,
    });
    loader.present();
    this.userService.regiseter(value).then(data => {
      if(data.status!=200){
        this.toastCtrl.create({message: "请求错误", duration: 4500}).present();
        loader.dismiss();
        return false;
      }
      var result = JSON.parse(data['_body']);
      if(result.status==1){
        this.toastCtrl.create({message:result.msg, duration: 4500}).present();
        loader.dismiss();
        return false;
      }
      if(result.status==0){
        loader.dismiss();
        this.toastCtrl.create({message:"注册成功,已跳转登陆!", duration: 4500}).present();
        this.navCtrl.push(Login, {
          phone : value.phone,
          password:value.password,
        });
      }
    });

  }

}
